package com.jgp.sys.utils;

import com.jgp.common.pojo.LabelValue;
import com.jgp.mico.client.MicroClient;
import com.jgp.mico.client.UriVariableStyle;
import com.jgp.sys.props.AttrPropBean;
import com.jgp.sys.props.InvokeRemotePropBean;
import com.jgp.sys.service.AttributeService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.*;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/3/13
 */
@Log4j2
public class DropUtil {
    
    public static Map<String, LabelValue> get(String activeKey) {
        if (StringUtils.isBlank(activeKey)) {
            return null;
        } else {
            List<LabelValue> list = getList(activeKey);
            if (Objects.isNull(list)) {
                return null;
            } else {
                Map<String, LabelValue> map = new HashMap();
                list.forEach(lv -> {
                    map.put(lv.getValue(),lv);
                });
                return map;
            }
        }
    }
    
    public static List<LabelValue> getList(String activeKey) {
        AttributeService attributeService = SpringContextUtil.getBean(AttributeService.class);
        if (StringUtils.isBlank(activeKey)) {
            return null;
        } else {
            List<LabelValue> list;
            AttrPropBean propBean = SpringContextUtil.getBean(AttrPropBean.class);
            if(ifInvokeFromRemote(propBean)){
                MicroClient microClient = SpringContextUtil.getBean(MicroClient.class);
                LinkedHashMap<String,Object> uriVariables = new LinkedHashMap<>();
                uriVariables.put("activeKey",activeKey);
                try {
                    list = microClient.postList(propBean.getMicroAppName(), "/sys/param-api-ctl/query-list-by-active-key", LabelValue.class, UriVariableStyle.KEY_VALUE_STYLE, uriVariables);
                } catch (IOException e) {
                    list = new ArrayList<>();
                    log.error("远程调用下拉数据出错！",e);
                }
            }else {
                list = attributeService.queryLabelValuesByActiveKey(activeKey);
            }
            return list;
        }
    }
    
    public static Boolean ifInvokeFromRemote(InvokeRemotePropBean propBean){
        MicroClient client = SpringContextUtil.getBean(MicroClient.class);
        if(Objects.isNull(client)) return false;
        return Objects.nonNull(client)&&Objects.nonNull(propBean)&&StringUtils.isNotBlank(propBean.getMicroAppName());
    }
    
}
